import os
import socket
import ssl
from typing import Tuple, List
import requests

HOST = "gpt.yunstorm.com"
PORT = 443
BASE_URL = f"https://{HOST}"
TIMEOUT: Tuple[float, float] = (100, 100)  # (connect, read)

def print_env_proxies():
    print("\n=== Proxy env ===")
    for k in ["HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"]:
        if k in os.environ:
            print(f"{k}={os.environ[k]}")
    print("===============")

def resolve_all(host: str) -> List[tuple]:
    infos = socket.getaddrinfo(host, PORT, proto=socket.IPPROTO_TCP)
    addrs = []
    for fam, stype, proto, canonname, sockaddr in infos:
        addrs.append((fam, sockaddr[0]))
    return addrs

def test_tcp_connect(ip: str, port: int, timeout: float = 10.0):
    print(f"\n- TCP connect to {ip}:{port} (timeout={timeout}s)")
    s = socket.socket(socket.AF_INET6 if ":" in ip else socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(timeout)
    try:
        s.connect((ip, port))
        print("  ✅ TCP connected")
    except Exception as e:
        print(f"  ❌ TCP failed: {e}")
    finally:
        s.close()

def test_tls_handshake(ip: str, server_hostname: str, timeout: float = 10.0):
    print(f"- TLS handshake with SNI={server_hostname} at {ip}:{PORT}")
    raw = socket.socket(socket.AF_INET6 if ":" in ip else socket.AF_INET, socket.SOCK_STREAM)
    raw.settimeout(timeout)
    ctx = ssl.create_default_context()
    try:
        raw.connect((ip, PORT))
        with ctx.wrap_socket(raw, server_hostname=server_hostname) as ssock:
            cert = ssock.getpeercert()
            print("  ✅ TLS ok, subject:", cert.get("subject"))
    except Exception as e:
        print(f"  ❌ TLS failed: {e}")
    finally:
        raw.close()

def http_get(path: str, timeout: Tuple[float, float] = TIMEOUT):
    url = BASE_URL + path
    print(f"\n=== HTTP GET {url} ===")
    try:
        r = requests.get(url, timeout=timeout)
        print(f"  ✅ Status: {r.status_code}")
        print(f"  Body preview: {r.text[:200]}")
    except requests.exceptions.ConnectTimeout:
        print("  ❌ ConnectTimeout (TCP/TLS阶段未建立)")
    except requests.exceptions.ReadTimeout:
        print("  ❌ ReadTimeout (已连上但读取超时)")
    except requests.exceptions.RequestException as e:
        print(f"  ❌ Other requests error: {e}")

if __name__ == "__main__":
    print_env_proxies()

    # 1) DNS 解析
    print("\n=== DNS resolve ===")
    addrs = resolve_all(HOST)
    for fam, ip in addrs:
        fam_str = "IPv6" if fam == socket.AF_INET6 else "IPv4"
        print(f"- {fam_str} -> {ip}")

    # 2) 逐个 IP 测 TCP & TLS
    for _, ip in addrs:
        test_tcp_connect(ip, PORT, timeout=10.0)
        test_tls_handshake(ip, HOST, timeout=10.0)

    # 3) HTTP 请求（分别测 / 与 API 路径）
    http_get("/")
    http_get("/openai/deployments/gpt-4o-mini/chat/completions?api-version=2025-01-01-preview")
